<template>
  <div>
    <nut-tabs background="#fff" title-scroll v-model="orderType" type="smile" swipeable>
      <nut-tab-pane v-for="(item, index) in orderTabs" :pane-key="item.value" custom-class="custom-tabpane" :key="index"
        :title="item.label">
        <div px-16rpx v-if="isShow">
          <div my-20rpx overflow-hidden p-32rpx v-for="(item, orderIndex) in orderList" :key="orderIndex" rounded-24rpx
            bg-white>
            <order :res="item" v-if="item.orderItems.length <= 1" :orderTypeWay="true" :payPoint="item.payPoint">
              <template #footer>
                <div mt-24rpx flex flex-a-c justify-end gap-16rpx>
                  <nut-button size="small" v-if="item.groupAfterSaleStatus &&
                    (item.groupAfterSaleStatus === 'NOT_APPLIED' || item.groupAfterSaleStatus === 'PART_AFTER_SALE')"
                    type="default" @click.stop="refund(item)">退款/售后</nut-button>
                  <nut-button size="small" v-if="item.allowOperationVO.cancel" @click.stop="handleClick('cancel', item)"
                    type="default">取消订单</nut-button>
                  <nut-button size="small" v-if="item.allowOperationVO.showLogistics" type="default">查看物流</nut-button>
                  <nut-button size="small" v-if="item.allowOperationVO.rog" @click.stop="handleClick('deliver', item)"
                    type="primary" plain>确认收货</nut-button>
                  <nut-button size="small" type="primary"
                    v-if="item.allowOperationVO && item.allowOperationVO.pay">立即付款</nut-button>
                </div>
              </template>
            </order>

            <!-- 大于1个商品多行排列展示 -->
            <div @click="handleClickGoods(item)" v-if="item.orderItems.length > 1" flex flex-col>
              <div>
                <order :res="item" only-store>
                </order>
              </div>
              <div flex flex-j-sb>
                <div flex gap-8rpx flex-wrap>
                  <image rounded-md block w-108rpx h-108rpx v-for="(order, index) in item.orderItems" :key="index"
                    :src="order.image">
                  </image>
                </div>
                <div min-w-100rpx flex flex-a-c flex-col>
                  <div text-26rpx font-bold text-main-color v-if="item.flowPrice">
                    {{ unitPrice(item.flowPrice, '￥') }}
                  </div>
                  <div color-gray text-24rpx>共<span mx-4rpx>{{ groupNumCount(item) }}</span>件</div>
                </div>
              </div>
              <div mt-24rpx flex flex-a-c justify-end gap-16rpx>

                <nut-button size="small"
                  v-if="item.groupAfterSaleStatus &&
                    (item.groupAfterSaleStatus.includes('NOT_APPLIED') || item.groupAfterSaleStatus.includes('PART_AFTER_SALE'))"
                  type="default" @click.stop="refund(item)">退款/售后</nut-button>
                <nut-button size="small" v-if="item.allowOperationVO.cancel" @click.stop="handleClick('cancel', item)"
                  type="default">取消订单</nut-button>
                <nut-button size="small" v-if="item.allowOperationVO.showLogistics" type="default">查看物流</nut-button>
                <nut-button size="small" v-if="item.allowOperationVO.rog" @click.stop="handleClick('deliver', item)"
                  type="primary" plain>确认收货</nut-button>
                <nut-button size="small" type="primary"
                  v-if="item.allowOperationVO && item.allowOperationVO.pay">立即付款</nut-button>
              </div>
            </div>
          </div>
          <div v-if="!orderList.length" mt-100rpx>
            <empty text="暂无订单信息" />
          </div>
        </div>
      </nut-tab-pane>
    </nut-tabs>
    <!-- 确认收货 -->
    <nut-dialog title="提示" content="是否确认收货？" v-model:visible="showDeliver" @ok="handleSubmitDeliver" />
    <!-- 取消订单 -->
    <cancelModule :loading="cancelLoading" @click="handleSubmitCancel" ref="cancelRef" />
    <!-- 加载 -->
    <nut-toast ref="toastRef" />
  </div>
</template>

<script setup lang="ts">
import { getOrderList } from '@/api/member';
import order from '@/components/basic-template/order.vue';
import empty from '@/components/empty/index.vue';
import type { Search } from '@/constants/types';
import cancelModule from '@/pages/mine/order/cancel.vue';
import { confirmCancelOrder, confirmDeliver } from '@/pages/mine/order/operation';
import { unitPrice } from '@/utils/filters';
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app';
import type { ToastInst } from 'nutui-uniapp';
const isShow = ref(false)
const cancelLoading = ref<boolean>(false)
const cancelRef = ref<any>(null)
const orderType = ref<string>('')
const currentOrderInfo = ref<any>('')
const showDeliver = ref<boolean>(false)
const toastRef = ref<ToastInst>()
const orderTabs = [
  {
    label: "全部",
    value: "ALL"
  },
  {
    label: "未付款",
    value: "WAIT_PAY"
  },
  {
    label: "待发货",
    value: "WAIT_SHIP"
  },
  {
    label: "待收货",
    value: "WAIT_ROG"
  },
  {
    label: "已完成",
    value: "COMPLETE"
  },
  {
    label: "已取消",
    value: "CANCELLED"
  },
]
const searchForm = ref<Search>({
  pageNumber: 1,
  pageSize: 10,
  tag: orderType.value
})
const orderData = ref<any>('')
const orderList = ref<any>([])


watch(() => orderType.value, (val) => {
  searchForm.value.tag = val
  init()
})

// 退款售后
function refund(val: any) {
  uni.navigateTo({
    url: `/pages/mine/aftersale/list?orderSn=${val.sn}`,
  });
}

function handleClickGoods(goods: any) {
  uni.navigateTo({
    url: `/pages/mine/order/detail?sn=${goods.sn}`
  })
}

// 商品数量
function groupNumCount(goods: any) {
  return goods.orderItems.reduce((total: any, item: any) => total + Number.parseInt(item.num), 0)
}

async function init() {
  isShow.value = false
  orderList.value = []
  searchForm.value.pageNumber = 1
  await fetch()
}
function handleClick(type: string, order: any) {
  if (type === 'cancel') {
    cancelRef.value.show = true
    currentOrderInfo.value = order
  }
  if (type === 'deliver') {
    showDeliver.value = true
    currentOrderInfo.value = order
  }
}


// 确认收货
async function handleSubmitDeliver() {
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const operation = await confirmDeliver(currentOrderInfo.value.sn)
  toastRef.value?.hideToast();
  if (operation) {
    init();
  }
}

// 点击取消订单
async function handleSubmitCancel(reason: string) {
  cancelLoading.value = true
  const sn = currentOrderInfo.value.tradeSn
  const operation = await confirmCancelOrder(sn, reason)
  cancelLoading.value = false
  cancelRef.value.show = false

  if (operation) {
    init()
  }
}

async function fetch() {
  uni.stopPullDownRefresh();

  const res = await getOrderList(searchForm.value)
  isShow.value = true
  if (res.data.success) {
    orderData.value = res.data.result
    orderList.value.push(...res.data.result.records)
  }
}
onPullDownRefresh(() => {
  init()
})

onReachBottom(() => {
  if (orderData.value?.total > searchForm.value.pageNumber * searchForm.value.pageSize) {
    searchForm.value.pageNumber++;
    fetch()
  }
})

onLoad((options: any) => {
  orderType.value = options.tag || 'ALL'
})

onShow(() => {
  if (searchForm.value.tag) {
    init()
  }
  
})

</script>

<style scoped lang="scss">
.nut-tab-pane {
  padding: 0;
}
</style>
